from rest_framework.views import APIView
from django_redis import get_redis_connection
from meiduo_mall.libs.captcha.captcha import captcha
from . import constants
from django.http import HttpResponse
from rest_framework.response import Response
import random
from meiduo_mall.libs.yuntongxun.sms import CCP
from rest_framework.generics import GenericAPIView
from . import serializers
from celery_tasks.sms.tasks import send_sms_code
import logging

logger = logging.getLogger('django')


# Create your views here.
class ImageCodeView(APIView):
    """图片验证码视图"""

    def get(self, request, image_code_id):
        """获取图片验证码"""
        # 生成图片验证码
        text, image = captcha.generate_captcha()

        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')

        # 存储图片验证码内容
        redis_conn.setex('img_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 返回响应
        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(GenericAPIView):
    """短信验证码视图"""

    # 指定序列化器类
    serializer_class = serializers.ImageCodeCheckSerializer

    def get(self, request, mobile):
        # 获取序列化器类对象，传入查询字符串获取的参数给序列化器进行校验
        serializer = self.get_serializer(data=request.query_params)

        # 进行字段的校验
        serializer.is_valid(raise_exception=True)

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        print(sms_code)
        # 使用日志记录短信验证码
        logger.info(sms_code)
        # 存储短信验证码
        redis_conn = get_redis_connection('verify_codes')
        # 短信验证码
        # redis_conn.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 短信发送标志
        # redis_conn.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 定义管道
        pl = redis_conn.pipeline()
        # 短信验证码
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 短信发送标志
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 执行数据库操作
        pl.execute()

        # 发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], constants.SMS_CODE_TEMPLATE)

        # 调用异步任务，将任务发布到broker中
        # 使用delay函数
        send_sms_code.delay(mobile, sms_code)

        # 返回响应
        return Response({'message': 'OK'})
